# Python includes
import sys
import DocXMLRPCServer
import gettext
import os

# Locale installing
gettext.install('pytachok','locale')

# Core classes include
from connection import *
from writer import *
from users import *
from textmessage import *
from servermessage import *
from chatrooms import *
            
class Settings:
    def load():
        pass

    def save():
        pass

class ChatAPI:
    def _server_message_(self, t):
        return self.server_messages.get(t)
    
    def _getmodes(self):
        return ['XMLRPC', 'Socket']

    def _getlogtypes(self):
        return ['XML', 'Text']
    
    def __init__(self, mode, logtype):
        self.users = Users()
        self.connection = Connection()
        self.server_messages = ServerMessages()
        self.settings = Settings()
        self.rooms = ChatRooms()
        modes = self._getmodes()
        logtypes = self._getlogtypes()
        if mode in modes:
            self.mode = mode
            self.connection = eval(mode + "Connection")()
        else:
            print self._server_message_("wrong_mode")
        if logtype in logtypes:
            self.logtype = logtype
            self.log = Log(logtype)
        else:
            print self._server_message_("wrong_logtype")
            
    def Login(self, name, password):
        '''Login to the chat server with name and password'''
        user = self.users.search(name, "all")
        if user == 0:
            print _("User \'" + name + "\' with password \'" + password + "\' was trying to login in. Rejecting. Can't find this user in database.")
            return self._server_message_("user_not_exists");
        else:
			if self.users.search(name, "online") == 0:
				print _("User \'" + name + "\' with password \'" + password + "\' Logged in!")
				self.users.login(user)
				return self._server_message_("logged_in");
			else:
				return self._server_message_("already_logged_in");

    def EnterRoom(self, room, roompass, name, password):
        '''Enter chat room'''
        room = self.rooms.search(room)
        if room != 0:
            if room.password == roompass:
                ok = self.rooms.enter(room, User(name, password))
                if ok == 0:
                    return self._server_message_("entered_room")
                else:
                    return self._server_message_("already_in_room")
            else:
                return self._server_message_("wrong_room_pass")
        else:
            return self._server_message_("wrong_room")

    def LeaveRoom(self, room, name, password):
        '''Leave a room'''
        room = self.rooms.search(room)
        if room != 0:
            self.rooms.kick(room, User(name, password))
            return self._server_message_("left_room")
        else:
            return self._server_message_("wrong_room")
            
    def CreateRoom(self, room, roompass, visible, name, password):
        '''Create a room. You can set room password protected or invisible to search.'''
        user = self.users.search(name, "online")
        if user != 0:
			if self.rooms.search(room) == 0:
				self.rooms.create(ChatRoom(room, roompass, visible, User(name, password)))
				return self._server_message_("created_room")
			else:
				return self._server_message_("room_exist")
        else:
            return self._server_message_("not_logged_in");
        
    def GetRooms(self, name, password):
        '''Get chat rooms list'''
        user = self.users.search(name, "online")
        if user != 0:
            print _("User \'" + name + "\' asked for rooms list")
            return self.rooms.getall()
        else:
            print _("Not logged in!")
            return self._server_message_("not_logged_in");
        
    def WhoIsIn(self, room = "main"):
        '''Show users online. Pass $room$ parameter to see users in room'''
        if room == "main":
            return self.users.getonline("array")
        else:
            r = self.rooms.search(room) 
            if r != 0:
                return r.getonline("array")
            else:
                return self._server_message_("wrong_room");

    def Message(self, name, password, text, room = "main"):
        '''Send message'''
        user = self.users.search(name, "online")
        if user == 0:
            print _("This user is not logged in.")
            return self._server_message_("not_logged_in");
        else:
            if room == "main":
                print name, ":", text
                message = TextMessage(name, text, "main")
            else:
                print room, ":::", name, ":", text
                message = TextMessage(name, text, room)
            self.log.add(message)
            return self._server_message_("message_arrived");

    def Logout(self, name, password):
        '''Logout from the server'''
        user = self.users.search(name, "online")
        if user == 0:
            print _("This user is not logged in.")
            return self._server_message_("not_logged_in");
        else:
            self.users.kick(user)
            self.rooms.kickall(user)
            print _("User " + user.Name + " logout.")
            return self._server_message_("logged_out");
        
    def Register(self, name, password):
        '''Register username on the server'''
        user = self.users.search(name, "all")
        if user != 0:
            print _("User \'" + user.Name + "\' already exist! Select another name please.") 
            return self._server_message_("user_exist")
        else:
            print _("Registering user \'" + name + "\' with password \'" + password + "\'")
            self.users.register(User(name, password))
            return self._server_message_("register_ok")
    
port = 9999
DocXMLRPCServer.allow_reuse_address = 1
handler = DocXMLRPCServer.DocXMLRPCServer(("localhost", port))
api = ChatAPI("XMLRPC", "Text")
handler.register_instance(api)
print "Started server on port",port,"..."
handler.serve_forever()

